package com.everydayflash.cart.points3d {
	import com.everydayflash.cart.core.AbstractSketch;
	
	import flash.filters.BlurFilter;
	import flash.geom.ColorTransform;
	import flash.geom.Matrix3D;
	import flash.geom.PerspectiveProjection;
	import flash.geom.Point;
	import flash.geom.Vector3D;		

	/**
	 * @author bartekd
	 */
	public class Points3D extends AbstractSketch {
		
		private var innerPts:Vector.<Vector3D>;		private var outerPts:Vector.<Vector3D>;
		private var projection:Matrix3D;
		private var angleX:Number = 0;		private var angleY:Number = 0;
		private var matrix:Matrix3D;

		override protected function init():void {
			var p:PerspectiveProjection = new PerspectiveProjection();
			p.focalLength = 400;
			projection = p.toMatrix3D();
			matrix = new Matrix3D();
			
			
			innerPts = new Vector.<Vector3D>();			outerPts = new Vector.<Vector3D>();
			
			for (var i:int = 0; i <1500; i++) {
				var rd:Number = 180;				var rdo:Number = 200 + Math.random() * 60;
				
				var r:Vector3D = new Vector3D(rdpos, rdpos, rdpos);
				r.normalize();
				
				var ir:Vector3D = r.clone();
				ir.x *= rd;				ir.y *= rd;				ir.z *= rd;
				innerPts.push(ir);
				
				var or:Vector3D = r.clone();
				or.x *= rdo;
				or.y *= rdo;
				or.z *= rdo;
				outerPts.push(or);
			}
			
			
		}
		
		private function get rdpos():Number {
			return 1 - (Math.random() * 2);
		}
		
		override protected function draw():void {
			canvas.graphics.clear();

			angleX -= (mouseX - sw/2) / sw/2 * 10;			angleY += (mouseY - sh/2) / sh/2 * 10;

			matrix.identity();
			matrix.appendRotation(angleX, new Vector3D(0, 0, 1));			matrix.appendRotation(angleY, new Vector3D(1, 0, 0));
			matrix.appendTranslation(0, 0, 350);

			for (var i:int = 0;i < innerPts.length; i++) {
				var iv:Vector3D = innerPts[i];
				var ov:Vector3D = outerPts[i];				
				iv = matrix.transformVector(iv);				ov = matrix.transformVector(ov);
				
				if(iv.z < ov.z) continue;
				
				var vz:Number = 1 - (iv.z / 250);
				vz = Math.min(1, vz);
				vz = Math.max(0, vz);
				canvas.graphics.lineStyle(2, 0xff0000, vz);
				
				iv = projection.transformVector(iv);				ov = projection.transformVector(ov);
				
				iv.project();				ov.project();
				
				canvas.graphics.moveTo(sw/2 + iv.x, sh/2 + iv.y);				canvas.graphics.lineTo(sw/2 + ov.x, sh/2 + ov.y);
			}
			
			bcanvas.draw(canvas);
			bcanvas.applyFilter(bcanvas, bcanvas.rect, new Point(), new BlurFilter(8,8,1));
			bcanvas.colorTransform(bcanvas.rect, new ColorTransform(1,1,1,.8));
		}
	}
}
